define(function(require, exports, module){
	
	/**
     * @name popMaterial
     * @class 封装素材预览or编辑or删除弹框方法。
     * @requires showmaterial
     */
	initMaterial = function(option){
		var op = $.extend({
				btn: '.previewbtn',
				material_id: '',
				action: 'preview',		//预览preview | 编辑edit | 删除delete
				success: null,
				error: null,
			}, option);
		
		if(semi.utils.isEmpty(op.btn) || typeof op.btn!='string')return;
		
		$(document).off('click',op.btn).on('click', op.btn, function(){
        	var $this = $(this), material_id = op.material_id;
        	if(semi.utils.isEmpty(material_id)){
        		material_id = $this.parents('tr:first').attr('material_id');
    		}
        	if(semi.utils.isEmpty(material_id)){
        		seajs.log('未获取到必选参数：material_id');
        		return;
        	}
        	
        	//删除素材
        	if(!semi.utils.isEmpty(op.action) && op.action=='delete'){
        		seajs.log('Error:暂不提供素材删除功能！')
        		return;
            	var $dlg = $dialog.confirm({
            		title: '素材删除',
                    content: '您确定要删除该素材吗？',
                    ok: function(){
                    	var $dlg = this;
                    	$ajax.ajax({
                    		url: '/trp/material/do_delete/',
                    		data: JSON.stringify({
                    			material_id: material_id
                    		}),
                    		contentType : 'application/json',
                            type : 'POST',
                            dataType : 'json',
                            success: function(){
                            	$dlg.close().remove();
                            	$dialog.alert('删除素材成功！','success');
                            	if(!semi.utils.isEmpty(op.success) && $.isFunction(op.success))op.success.call();
                            },
    	                    error: function(){
    	                    	$dlg.close().remove();
    	                    	$dialog.alert('删除素材失败，请稍后重试！','warning');
    	                    	if(!semi.utils.isEmpty(op.error) && $.isFunction(op.error))op.error.call();
    	                    }
                    	});
                    	return false;
                    }
            	});
            	$.extend($dlg,{material_id:material_id});
        		return;
        	}
        	
        	
        	var isEdit = false
        	if(!semi.utils.isEmpty(op.action) && op.action=='edit')isEdit = true;
        	
        	var defOption = {
        		title: '素材预览',
        		width: '500px',
        		onshow: function(){
        			var $d = this, $node = $(this.node);
        			$ajax.ajax({
                		url: '/trp/material/get_material/',
                		data: JSON.stringify({material_id: material_id}),
                		contentType : 'application/json',
                        type : 'POST',
                        dataType : 'json',
                        success: function(data){
                			$d.content(['<div class=" pop-form form-group">',
	                    					'<div class="form_item" style="height:auto;">',
	                    						'<label class="form_label">预览：</label>',
	                    						'<div class="form_ctrl mcontent"></div>',
	                    					'</div>',
	                    					'<div class="form_item">',
	                    						'<label class="form_label">名称：</label>',
	                    						'<div class="form_ctrl mname"></div>',
	                    					'</div>',
	    	            					'<div class="form_item">',
	    	            						'<label class="form_label">标签：</label>',
	    	            						'<div class="form_ctrl tags"></div>',
	    	            					'</div>',
	    	            					'<div class="form_item">',
	    	            						'<label class="form_label">链接地址：</label>',
	    	            						'<div class="form_ctrl mlandingpage"></div>',
	    	            					'</div>',
	    	            					'<div class="form_item">',
			            						'<label class="form_label">频次控制：</label>',
			            						'<div class="form_ctrl mfrequency"></div>',
			            					'</div>',
	                					'</div>'].join(''));
	            			
                			var d = data;//{"status": 0, "name": "psb.jpg", "url": "http://d189.mzhen.cn/material/review/8a2b28ec73ad7f287e70f0d6c3bfc72d.jpg", "height": 640, "width": 640, "reason": "", "landingpage": "http://www.baidu.com", "id": 3612, "statusCode": 200}
	              		  	require.async('./showmaterial', function($showmaterial){
	              		  		$showmaterial.init({
	              		  			item: $('.mcontent',$node),
	                      		  	data: d
	              		  		});
	              		  		var _tags = '';
		              		  	if(!semi.utils.isEmpty(d.tags)){
	          		  				var _nameArr = [];
	          		  				$.each(d.tags, function(i,n){
	          		  					_nameArr.push(n.name);
	          		  				});
	          		  				_tags = _nameArr.join(',');
	          		  			}
	              		  		if(!isEdit){
	              		  			$('.mname',$node).html(d.name);
	              		  			$('.mlandingpage',$node).html('<a href="'+d.landingpage.toUrl()+'" title="'+d.landingpage+'" target="_blank" style="white-space:nowrap;">'+d.landingpage+'</a>');
	              		  			$('.mfrequency',$node).html(d.frequency);
	              		  			if(!semi.utils.isEmpty(_tags)){
	              		  				$('.tags',$node).html(_tags);
	              		  			}else{
	              		  				$('.tags',$node).html('<span class="gray">无</a>');
	              		  			}
	              		  			
	              		  			if($('.mlandingpage',$node).width()+20>$('.mlandingpage',$node).parent().width()-$('.mlandingpage',$node).siblings('.form_label').width()){
	              		  				$('.mlandingpage',$node).css({
	              		  					'width':$('.mlandingpage',$node).parent().width()-$('.mlandingpage',$node).siblings('.form_label').width()-20-30,
	              		  					'height':'50px',
	              		  					'overflow':'hidden'
	              		  				});
	              		  			}
	              		  			return;
	              		  		}
      		              		$('.mname',$node).append('<input type="text" class="form-control" placeholder="素材名称" name="picname" value="'+d.name+'">');
              		  			$('.tags',$node).append('<input type="text" class="form-control" placeholder="素材标签" name="pictags" value="'+_tags+'">');
              		  			$('.mlandingpage',$node).append('<input type="text" class="form-control" placeholder="链接地址" name="piclandingpage" value="'+d.landingpage+'">');
              		  			$('.mfrequency',$node).append('<input type="text" class="form-control" placeholder="素材名称" name="picfrequency" value="'+d.frequency+'">');
	              		  	});
	              		  	if(d.width>300){
	              		  		$d.width(d.width+200);
	              		  	}
	            		}
                	});
                },
                cancelValue: '关闭',
                cancel: true
            }
        	
        	//预览
        	if(!isEdit){
        		$dialog(defOption).showModal();
        		return;
        	}
        	
        	//修改素材
        	$dialog($.extend(defOption,{
        		title: '素材修改',
        		okValue: '保存',
        		ok: function(){
        			var $dlg = this, $node = $(this.node);
        			$ajax.ajax({
            			url : '/trp/material/do_modify/',
                		data: JSON.stringify({
                			material_id: material_id,
                			name: $('[name=picname]',$node).val(),
          				  	tags: $('[name=pictags]',$node).val(),
          				  	landingpage: $('[name=piclandingpage]',$node).val(),
          				  	frequency: $('[name=picfrequency]',$node).val(),
                		}),
                		contentType : 'application/json',
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('修改素材成功！','success');
                        	if(!semi.utils.isEmpty(op.success) && $.isFunction(op.success))op.success.call();
                        },
                    	error: function(){
                      		$dialog.alert('修改素材失败，请稍后重试！','warning');
                      		if(!semi.utils.isEmpty(op.error) && $.isFunction(op.error))op.error.call();
                      	}
                	});
        		}
        	})).showModal();
        	
        });
	}
	
	return{
		init: initMaterial
	}
});